//
//  PoppverAnimator.swift
//  LX_weibo
//
//  Created by LTT❤️ on 15/7/3.
//  Copyright © 2015年 LTT. All rights reserved.
//

import UIKit

class PoppverAnimator: NSObject,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning
{
    
   // 
    
    var presentFrame = CGRectZero
    var isPressend = false
    
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        
        let pc = PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting)
        pc.presentFrame = presentFrame
        
        return pc
        
    }
    //返回提供Model动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPressend = true
        return self
    }
    //dismiss
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPressend = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 1.5
    }
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        
        
        print(fromVC)
        print(toVC)
        //判断是展现还是dismis
        
        
        if isPressend{
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            //1.将 toView  = 添加到容器视图
            transitionContext.containerView()?.addSubview(toView)
            
            toView.transform = CGAffineTransformMakeScale(1.0, 0)
            toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
                toView.transform = CGAffineTransformIdentity
                }, completion: { (_) -> Void in
                    transitionContext.completeTransition(true)
            })
        }else {
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
            fromView.removeFromSuperview()
            transitionContext.completeTransition(true)
        }
        
    }
    
    
}
